<template>
  <div v-loading="loading">
    <!-- 分销商列表的产品发布 -->
    <!--点击扩展按钮对应的弹出框-->
    <vol-box :model.sync="model" title="产品发布" :width="950" :height="500">
      <VolForm
        ref="myform"
        :loadKey="loadKey"
        :formFileds="formFileds"
        :formRules="formRules"
        :labelWidth="100"
      ></VolForm>
      <div class="toolbar">
        <div class="title form-text">
          <span>
            <Icon type="md-list-box" />
            发布商品
          </span>
        </div>
        <!--明细表格按钮-->
        <div class="btns"></div>
      </div>
      <!-- 表格  -->
      <VolTable
        style="flex: 1"
        :height="240"
        ref="table"
        :loadKey="true"
        :columns="columns"
        :pagination-hide="true"
        :index="true"
        :summary="true"
        :single="false"
        :tableData="tableData"
        :isPaging="true"
        :paginationHide="false"
      >
      </VolTable>
      <!-- 添加slot槽覆盖footer的按钮，添加新的按钮 -->
      <div slot="footer">
        <Button type="error" @click="getFirstRow" icon="md-checkmark"
          >保存</Button
        >
        <Button type="success" @click="resetForm" icon="md-refresh"
          >重置</Button
        >
        <Button type="info" @click="close" icon="md-close">关闭</Button>
      </div>
    </vol-box>
  </div>
</template>
<script>
import data from "../../../views/builder/builderData";
export default {
  components: {
    VolBox: () => import("@/components/basic/VolBox.vue"),
    VolForm: () => import("@/components/basic/VolForm.vue"),
    VolTable: () => import("@/components/basic/VolTable.vue"),
  },
  data() {
    return {
      loading: false,
      loadKey: true,
      model: false,
      formFileds: {
        distributionid: "",
        timeContainer: [],
        status: "",
        isSellLikeHot: 1,
        code: "",
        sellingRulesid: "",
        refundrulesid: "",
        verificationrulesid: "",
        effectiveStartDate: "",
        effectiveEndDate: "",
        supplierid: "",
        producttype: [],
        productid: "",
        spare1: 0,
        creator: "",
        createID: "",
        createDate: "",
        modifier: "",
        modifyDate: "",
        modifyID: "",
        merchantCode: "",
        merchantName: "",
        auditStatus: 0
      },
      //   url: "", //后从加载数据的url
      formRules: [
        [
          {
            title: "分销商",
            field: "distributionid",
            type: "text",
            colSize: 4,
            disabled: true,
            hidden: true,
          },
          {
            title: "分销商",
            required: true,
            field: "distributionName",
            type: "text",
            colSize: 4,
            disabled: true,
          },
          {
            title: "起止时间",
            required: true,
            field: "timeContainer",
            colSize: 4,
            type: "datetime",
            range: true,
          },
          {
            title: "状态",
            type: "text",
            field: "status",
            colSize: 2,
            disabled: true,
          },
          {
            title: "是否热销",
            required: true,
            field: "isSellLikeHot",
            type: "switch",
            colSize: 2,
          },
        ],
        [
          {
            title: "企业码",
            type: "text",
            field: "code",
            colSize: 6,
            disabled: true,
            hidden: true,
          },
        ],
        [
          {
            title: "售卖规则",
            required: true,
            field: "sellingRulesid",
            type: "select",
            dataKey: "mall_sellingrules",
            colSize: 4,
          },
          {
            title: "退改规则",
            required: true,
            field: "refundrulesid",
            type: "select",
            dataKey: "Mall_refundrules",
            colSize: 4,
          },
          {
            title: "核销规则",
            required: true,
            field: "verificationrulesid",
            type: "select",
            dataKey: "mall_verificationrules",
            colSize: 4,
          },
        ],
        [
          {
            title: "开始时间",
            field: "effectiveStartDate",
            type: "datetime",
            colSize: 6,
            hidden: true,
          },
          {
            title: "结束时间",
            field: "effectiveEndDate",
            type: "datetime",
            colSize: 6,
            hidden: true,
          },
        ],
        [
          {
            title: "产品类型",
            required: true,
            field: "producttype",
            type: "cascader",
            dataKey: "tree_protype",
            orginData: [],
            data: [],
            colSize: 4,
          },
          {
            title: "产品名称",
            field: "productid",
            type: "select",
            colSize: 4,
            data: [],
            disabled: true,
          },
          {
            title: "库存数",
            required: true,
            field: "spare1",
            type: "number",
            colSize: 4,
            min: 0,
          },
        ],
      ],
      // 列表数据
      tableData: [],
      columns: [
        {
          field: "id",
          title: "主键",
          type: "string",
          width: 90,
          hidden: true,
          readonly: true,
          require: true,
          align: "left",
        },
        //    {field:'distri_productid',title:'产品创建',type:'string',width:90,align:'left',edit:{type:'text'},sortable:true},
        //    {field:'goodid',title:'商品id',type:'string',width:90,align:'left'},
        {
          field: "spare2",
          title: "商品编码",
          type: "string",
          width: 150,
          align: "left",
          fixed: "left",
        },
        {
          field: "spare1",
          title: "商品名称",
          type: "string",
          width: 150,
          align: "left",
          fixed: "left",
        },
        {
          field: "offlineCode",
          title: "线下编码",
          type: "string",
          require: true,
          width: 150,
          edit: { type: "text" },
          align: "left",
        },
        {
          field: "sellingPrice",
          title: "门市价",
          type: "string",
          width: 100,
          edit: { type: "decimal" },
          align: "left",
        },
        {
          field: "preferentialPrice",
          title: "优惠价",
          type: "string",
          width: 90,
          edit: { type: "decimal" },
          align: "left",
        },
        {
          field: "vipPrice",
          title: "会员价",
          type: "string",
          width: 90,
          edit: { type: "decimal" },
          align: "left",
        },
        {
          field: "settlementPrice",
          title: "结算价",
          type: "string",
          width: 90,
          edit: { type: "decimal" },
          align: "left",
        },
        {
          field: "channelPrice",
          title: "渠道价",
          type: "string",
          width: 90,
          edit: { type: "decimal" },
          align: "left",
        },
        // {field:'attr',title:'属性',type:'string',edit:{type:'text'},width:220,align:'left'},
        //    {field:'modifier',title:'修改人',type:'string',width:180,edit:{type:'text'},align:'left'},
        //    {field:'modifyDate',title:'修改时间',type:'datetime',width:135,align:'left',sortable:true},
        //    {field:'modifyID',title:'修改人ID',type:'int',width:90,hidden:true,align:'left'},
        // {field:'createDate',title:'创建时间',type:'datetime',width:135,align:'left',sortable:true},
        // {field:'createID',title:'创建人ID',type:'int',width:90,hidden:true,align:'left'},
        //  {field:'creator',title:'创建人',type:'string',width:180,edit:{type:'text'},align:'left'},
        {
          field: "isAvailable",
          title: "是否可用",
          type: "int",
          edit: { type: "switch" },
          width: 90,
          align: "left",
        },
        //    {field:'spare1',title:'扩展字段1',type:'string',width:220,align:'left'},
        //    {field:'spare2',title:'扩展字段1',type:'string',width:220,align:'left'},
        //    {field:'spare3',title:'扩展字段1',type:'string',width:220,align:'left'},
        //    {field:'spare4',title:'扩展字段1',type:'string',width:220,align:'left'},
        //    {field:'spare5',title:'扩展字段1',type:'string',width:220,align:'left'},
        //    {field:'spare6',title:'扩展字段1',type:'string',width:220,align:'left'},
        //    {field:'spare7',title:'扩展字段1',type:'string',width:220,align:'left'},
        //    {field:'spare8',title:'扩展字段1',type:'string',width:220,align:'left'}
      ],
    };
  },
  created() {
    this.http
      .post("/api/Dictionary/GetVueDictionary", ["tree_protype"])
      .then((res) => {
        // console.log(res[0].data);
        res[0].data.forEach((i) => {
          i.label = i.value;
        });
        // console.log(res[0].data);
        this.formRules.forEach((i) => {
          i.forEach((x) => {
            if (x.field == "producttype") {
              x.data.push(
                ...this.base.convertTree(
                  JSON.parse(JSON.stringify(res[0].data)),
                  (node, data, isRoot) => {
                    node.label = node.value;
                    node.value = node.key;
                  }
                )
              );
              x.orginData.push(...res[0].data);
            }
          });
        });
      });
  },
  methods: {
    getFormOption(field) {
      let option;
      this.formRules.forEach((x) => {
        x.forEach((item) => {
          if (item.field == field) {
            option = item;
          }
        });
      });
      return option;
    },
    open(row) {
      console.log("行数据", row);
      this.$refs.myform.reset(); //重置表单
      this.$refs.table.reset(); //重置表格
      this.getModel(row.distributorCode); //分销商详情
      this.formFileds.distributionid = row.distributorCode; //分销商
      this.formFileds.distributionName = row.distributorName; //分销商名称
      let productidOption = this.getFormOption("productid"); //产品名称
      productidOption.data = [];
      productidOption.disabled = true;
      //   产品类型绑定 change 事件
      let producttypeOption = this.getFormOption("producttype");
      producttypeOption.onChange = (val, selectdata) => {
        this.formFileds[productidOption.field] = "";
        if (val.length != 0) {
          this.getProduct(val[val.length - 1], productidOption);
        }
      };
    },
    // 获取产品名称下拉框数据
    getProduct(val, productidOption) {
      // this.formFileds.distributionid
      this.http
        .get("api/distriProducts/GetProducts?id=" + val + "&distriCode=" + this.formFileds.distributionid, "", true)
        .then((reslut) => {
          productidOption.data = [];
          if (reslut.data.length < 1) {
            productidOption.disabled = true; //产品名称 改为不可编辑
          } else {
            reslut.data.forEach((item) => {
              let items = {};
              items.value = item.dicName;
              items.key = item.dicValue;
              productidOption.data.push(items);
              //产品名称绑定 change 事件
              productidOption.onChange = (val, item) => {
                this.$refs.table.reset();
                if (val === undefined) {
                } else {
                  this.getProductModel(val);
                }
              };
              productidOption.disabled = false; //产品名称 改为可编辑
            });
          }
        });
    },
    getModel(val) {
      //根据分销商ID获取分销商的详细信息
      this.http
        .get("api/distriProducts/GetDistributors?id=" + val, {}, true)
        .then((reslut) => {
          if (reslut) {
            this.formFileds.status = reslut.data.status;
            this.formFileds.code = reslut.data.distributorCode;

            // let time = new Date().getTime();
            // let endtime = new Date(reslut.distributorEndTime).getTime();
            // let starttime = new Date(reslut.distributorStartTime).getTime();
            // if (time >= starttime && time <= endtime) {
            //   this.formFileds.status = "正常";
            // } else {
            //   this.formFileds.status = "已过期";
            // }
            // this.formFileds.code = reslut.data.distributorCode; //企业码
            this.model = true; //打开弹框
          }
        });
    },
    getProductModel(val) {
      //根据产品ID获取产品下所有商品
      this.http
        .get("api/distriProducts/getGoods?id=" + val, {}, true)
        .then((reslut) => {
          this.formFileds.supplierid = reslut.data.disCode;
          reslut.data.goodList.forEach((item) => {
            let dataitem = {};
            dataitem.spare1 = item.name;
            dataitem.spare2 = item.code;
            dataitem.goodid = item.goodId;
            dataitem.sellingPrice = item.originalPrice;
            dataitem.preferentialPrice = item.preferentialPrice;
            dataitem.vipPrice = 0;
            dataitem.settlementPrice = 0;
            dataitem.channelPrice = 0;
            dataitem.offlineCode = item.offlineCode;
            dataitem.isAvailable = 1;
            this.$refs.table.addRow(dataitem);
          });
        });
    },
    // 保存按钮
    getFirstRow() {
      console.log("aaa", this.formFileds, this.tableData);
      this.$refs.myform.validate(() => {
        if (!this.tableData.length) {
          return this.$Message.error('请选择有商品的产品');
        }
        if (this.formFileds.timeContainer.length > 1) {
          this.formFileds.effectiveStartDate = this.formFileds.timeContainer[0];
          this.formFileds.effectiveEndDate = this.formFileds.timeContainer[1];
        }
        if (Array.isArray(this.formFileds.producttype)) {
          this.formFileds.producttype =
            this.formFileds.producttype[this.formFileds.producttype.length - 1];
        }
        let params = {
          delKeys: null,
          detailData: this.tableData,
          mainData: this.formFileds,
        };
        this.http.post("/api/distriProducts/Add", params, true).then((res) => {
          if (res.status) {
            this.close(); //关闭弹窗
            this.$Message.success(res.message);
          } else {
            this.$Message.error(res.message);
          }
        });
        //     //   // this.loading = true;
        //     console.log("shuju", this.formFileds);
        //     that.$parent.jsEvent(this.formFileds);
      });
    },
    close() {
      this.model = false;
      //  let that= this.$store.getters.data().viewPageTest;
      //  that.$refs.table.load();
    },
    // 重置表单
    resetForm() {
      this.$refs.myform.reset();
    },
  },
};
</script>
<style lang="less" scoped>
.toolbar {
  padding: 3px 15px;
  width: 100%;
  display: flex;
  //  padding: 3px;
  border-top: 1px solid #eae9e9;
  // border-top-left-radius: 5px;
  // // background: #37aba0;
  // border-top-right-radius: 5px;
  // border: 1px solid #f1f1f1;
  .title {
    line-height: 28px;
    border-bottom: 2px solid #03a9f4;
    font-size: 14px;
    font-weight: bolder;
    margin-bottom: 0;
    color: #828282;
    .icon {
      color: #009688;
      font-size: 18px;
    }
  }
  .btns {
    line-height: 28px;
    flex: 1;
    text-align: right;
    margin-right: 12px;
    button {
      border: none;
      margin-left: 15px;
      border: 0px;
      color: #009688;
    }
    button:hover {
      color: #ff9800;
      border-color: #ff9800;
      border: none;
    }
  }
}
</style>
